package chpt09;

public class UnSynchronizedStaticThreadTest {
	public static void main(String[] args) throws InterruptedException {
		int n = 1000; // 执行次数
		Thread t1 = new Thread(new StaticAdder(n));
		Thread t2 = new Thread(new StaticAdder(n));
		Thread t3 = new Thread(new StaticAdder(n));
		Thread t4 = new Thread(new StaticSubtracter(n));
		Thread t5 = new Thread(new StaticSubtracter(n));
		Thread t6 = new Thread(new StaticSubtracter(n));

		t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();
		t1.join();t2.join();t3.join();t4.join();t5.join();t6.join();

		System.out.println("Counter.id="+StaticCounter.getId());
		System.out.println("main end");
	}
}

class StaticCounter {
	private static int id = 0;
	public static void addId() {
		id++;
	}
	public static void subtractId() {
		id--;
	}
	public static int getId() {
		return id;
	}
}

class StaticAdder implements Runnable {
	private int n; // 执行次数
	public StaticAdder(int n) {
		this.n = n;
	}
	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			StaticCounter.addId();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}

class StaticSubtracter implements Runnable {
	private int n;
	public StaticSubtracter(int n) {
		this.n = n;
	}
	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			StaticCounter.subtractId();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}
